package com.idea.relax.tool.core.tree;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author azhao
 */
public class TreeToList<T> extends ListTree<T> {
    private Logger logger = LoggerFactory.getLogger(TreeToList.class);

    public List<T> transfer(List<T> source) {
        if (check(source)) {
            logger.info("检查失败");
            return source;
        }
        init(source);
        try {
            for (T t : source) {
                T obj = cloneObject(t);
                id.set(obj, id.get(t));
                if (level != null) {
                    level.set(obj, 1);
                }
                list.add(obj);
                traverseTreeToList(t, levelNumber);
            }
            for (T t : list) {
                children.set(t, new ArrayList<>());
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return list;
    }

    public List<T> transfer(T source) {
        if (source == null) {
            return list;
        }
        List<T> treeList = new ArrayList<>();
        treeList.add(source);
        return transfer(treeList);
    }

    private void traverseTreeToList(T obj, int levelNumber) throws IllegalAccessException {
        List<T> childrenList = (List<T>) children.get(obj);
        ++levelNumber;
        if (childrenList != null && !childrenList.isEmpty()) {
            for (T o : childrenList) {
                parentId.set(o, id.get(obj));
                if (level != null) {
                    level.set(o, levelNumber);
                }
                list.add(o);
                traverseTreeToList(o, levelNumber);
            }
        }
    }
}
